#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from Utils.Logger import Logger, now_time
from Utils.PropertiesParsor import ParsePageProperty
from Config.GlobalVariables import ACTOYS_SEARCH_FORCE_WAIT, RESULTS_SEARCHRESULTS_PATH
from Framework.BrowserEngine import browserEngine
from PageObjects.ACToys.TransformerTradePage import TransformerTradePage
from PageObjects.ACToys.ACToysSearcherPage import ACToysSearcherPage
from PageObjects.WebWeiXin.WXHomePage import WXHomePage
from PageObjects.WebQQ.QQHomePage import QQHomePage
import time
import os
import unittest


class SearchACToys(unittest.TestCase):

    logger = Logger().get_logger()
    parse_string = ParsePageProperty().parse_string
    parse_locator = ParsePageProperty().parse_locator

    def setUp(self):
        self.logger.info('********************************** Start {0} **********************************'
                         .format(self._testMethodName))
        self.driver = browserEngine.get_driver()
        self.webwx = WXHomePage(self.driver)
        self.webqq = QQHomePage(self.driver)
        self.actoys = TransformerTradePage(self.driver)
        self.searcher = ACToysSearcherPage(self.driver)

    def tearDown(self):
        self.logger.info('********************************** End {0} **********************************'
                         .format(self._testMethodName))

    def force_wait(self, wait_time=ACTOYS_SEARCH_FORCE_WAIT):
        self.logger.info("Wait 15 seconds for forum's searching requirement")
        time.sleep(wait_time)

    def testSearch(self):
        self.logger.info("Clear search textbox")
        self.actoys.search_textbox().clear()
        search_content = self.searcher.parse_target_search_content_list()
        self.logger.info("Input search textbox: {0}".format(search_content[0]))
        self.actoys.search_textbox().send_keys(search_content[0])
        self.logger.info("Click search submit button")
        self.actoys.search_button().click()
        search_textbox_locator = self.parse_locator('ACToys.SearcherPage.search_textbox')
        self.logger.info("Wait search textbox display and clickable: {0}".format(search_textbox_locator))
        self.searcher.wait.element_clickable(search_textbox_locator)
        self.force_wait()

        while self.actoys.search_textbox():
            for target_search_content in search_content:
                self.logger.info("Clear search textbox")
                self.searcher.search_textbox().clear()
                self.logger.info("Input search textbox: {0}".format(target_search_content))
                self.searcher.search_textbox().send_keys(target_search_content)
                self.logger.info("Click search submit button")
                self.searcher.search_button().click()
                self.logger.info("Record new search result in the 1st search page")
                all_search_results = [result.get_attribute("href") for result in self.searcher.search_results_links()]
                results_dict = ParsePageProperty().make_dict(range(len(all_search_results)), all_search_results)
                results_file_name = '{0}_{1}.json'.format(now_time, target_search_content)
                results_file_path = os.path.join(RESULTS_SEARCHRESULTS_PATH, results_file_name)
                if os.path.exists(results_file_path):
                    self.logger.debug("Search result file already existed")
                    previous_results_dict = ParsePageProperty.parse_search_result(results_file_path)
                    previous_search_results = list(previous_results_dict.values())
                    if all_search_results == previous_search_results:
                        self.logger.info("No new search result")
                    else:
                        self.logger.info("Found new search result")
                        for result in previous_search_results:
                            if result in all_search_results:
                                all_search_results.remove(result)
                        send_messages = "@王琪瑞 '{0}'有新帖子: {1}".format(
                            target_search_content, ",\n".join(all_search_results))
                        self.logger.info("Send new result {0} to Web WeiXin".format(send_messages))
                        self.webwx.send_messages(2, "喝吊扯", send_messages)
                        self.logger.info("Send new result {0} to Web QQ".format(send_messages))
                        self.webqq.send_messages(3, "么的吊丝", send_messages)
                else:
                    if len(all_search_results) >= 5:
                        send_messages = "@王琪瑞 初始化'{0}'搜索结果，最新的5个发布交易帖 url 是：{1}".format(
                            target_search_content, ", ".join(all_search_results[:5]))
                    elif 0 < len(all_search_results) < 5:
                        send_messages = "@王琪瑞 初始化'{0}'搜索结果，最新的几个发布交易帖 url 是：{1}".format(
                            target_search_content, ",\n".join(all_search_results))
                    elif len(all_search_results) == 0:
                        send_messages = "@王琪瑞 初始化'{0}'搜索结果，没有任何发布交易帖，如有必要，请检查搜索条件".format(
                            target_search_content)
                    self.logger.info("Send the 1st result {0} to Web WeiXin".format(send_messages))
                    self.webwx.send_messages(2, "喝吊扯", send_messages)
                    self.logger.info("Send the 1st result {0} to Web QQ".format(send_messages))
                    self.webqq.send_messages(3, "么的吊丝", send_messages)
                self.logger.info("Make new search result file: ".format(results_file_name))
                ParsePageProperty.make_search_result_json_file(results_dict, results_file_name)
                self.force_wait()

if __name__ == "__main__":
    unittest.main()
